package com.test.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pojo.User;

import java.util.ArrayList;

/**
 * @Author:huang
 * @Date: Created in 2021/5/15 19:43
 */
@RestController
public class FastJsonController {

    @RequestMapping("/j")
    public String fast(){
        ArrayList<User> userArrayList = new ArrayList<>();

        User user1 = new User("张三", 3);
        User user2 = new User("李四", 4);
        User user3 = new User("天祎", 43);
        userArrayList.add(user3);
        userArrayList.add(user1);
        userArrayList.add(user2);

        //java对象转JSON字符串
        String string = JSON.toJSONString(userArrayList);
        String string1 = JSON.toJSONString(user1);

        //JSON字符串转java对象
        User user = JSON.parseObject(string1, User.class);

        //java对象转JSON对象
        JSONObject json = (JSONObject)JSON.toJSON(user1);
        //System.out.println(json.getString("name"));

        //JSON对象转java对象
        User javaObject = JSON.toJavaObject(json, User.class);

        return string1;
    }
}
